package org.summerframework.component.note.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.summerframework.component.note.PlatformEnum;
import org.summerframework.component.note.config.AliyunNoteProperties;
import org.summerframework.component.note.manager.SendNoteService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author 石超
 * @version v1.0.0
 */
@Slf4j
public class AliyunSendNoteServiceImpl implements SendNoteService {

    private AliyunNoteProperties aliyunNoteProperties;

    public AliyunSendNoteServiceImpl(AliyunNoteProperties aliyunNoteProperties) {
        this.aliyunNoteProperties = aliyunNoteProperties;
    }

    @Override
    public void sendNote(String account, String nationCode, String signName, String templateCode, String templateContent, Map<String, Object> param) {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        DefaultProfile profile = DefaultProfile.getProfile(aliyunNoteProperties.getRegionId(), aliyunNoteProperties.getAccessKeyId(), aliyunNoteProperties.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonResponse response = null;
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(aliyunNoteProperties.getDomain());
        request.setVersion(aliyunNoteProperties.getVersion());
        request.setAction(aliyunNoteProperties.getAction());
        request.putQueryParameter("RegionId", aliyunNoteProperties.getRegionId());
        request.putQueryParameter("PhoneNumbers", account);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        log.warn("phone {}, templateParams {}, templateCode {}", account, param, templateCode);

        if (param != null) {
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        }
        try {
            response = client.getCommonResponse(request);
            JSONObject jsonNode = JSONObject.parseObject(response.getData());
            log.debug("短信接口返回的数据----------------" + response.getData());
            log.debug("code:" + jsonNode.get("Code"));
            log.debug("Message:" + jsonNode.get("Message"));
        } catch (ClientException e) {
            log.warn("发送短信异常", e);
        }
    }

    @Override
    public boolean isSupper(Integer platformCode) {
        return PlatformEnum.ALIYUN.isType(platformCode);
    }
}
